module Authenticator
protected
  # Returns whether the user is logged in
  # Loads @current_user with the user model if logged in
  def logged_in?
    !!current_<%=model_file_name%>
  end

  # Returns whether the user is logged in
  # Loads @current_user with the user model if logged in
  # Redirects appropriately if not logged in
  # To be used as a before_filter
  def login_required(rank=nil)
      (logged_in? && authorized?(rank)) || access_denied
  end

  # Check if the user is authorized
  # Modify to control or restrict acess
  def authorized?(rank=nil)
    logged_in? && (!rank || @current_user.roles.find_by_id(rank.id))
  end

  # Loads self.current_user with the user model if logged in
  # set to :false if login fails so future calls don't hit the database
  def current_<%=model_file_name%>
    @current_<%=model_file_name%> ||= (login_from_session || login_from_basic_auth) unless @current_<%=model_file_name%> == false 
  end

  # Attempts to login by the user id stored in the session
  def login_from_session
    <%= model_class_name %>.find(session[:<%=model_file_name%>_id]) if session[:<%=model_file_name%>_id]
  end

  # Attemps to login by basic authentication information
  # for restful clients
  def login_from_basic_auth
    authenticate_with_http_basic do |login, password|
      <%= model_class_name %>.authenticate login, password
    end
  end

  # Stores the given user id in the session
  # and loads @current_user with the new_user
  def current_<%=model_file_name%>=(new_user)
    session[:<%=model_file_name%>_id] = new_user ? new_user.id : nil
    @current_<%=model_file_name%> = new_user || :false
  end

  # Default behavior is to redirect to login screen
  def access_denied
    flash[:error] = "You must be logged in to access this page"
		store_location
    redirect_to new_session_url
  end

	# Store the URI of the current request in the session
	# We ca return to this location by calling redirect_back_or_default
	def store_location
		session[:return_to] = request.request_uri
	end

	# Redirect to the URI stored by the most recent store_location call or
	# to the passed default
	def redirect_back_or_default(default)
		redirect_to(session[:return_to] || default)
		session[:return_to] = nil
	end

  # Store the URI of the referer in this session
  # so we can return to this location by calling redirect_back_or_default
  # store_location is only useful if used before a redirect
  def store_referer
    session[:return_to] = request.referrer
  end

	# inclusion hook to make #current_<%=model_file_name%> and #logged_in?
	# available as ActionView helper methods
	def self.included(base)
		base.send :helper_method, :current_<%=model_file_name%>, :logged_in?
	end
end
